package com.teamawesome.hackathon.backend;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Scanner;

import android.util.Log;

public class ApiCalls {

	private final String APIKEY = "wd59v23gdaw63dchzycfn4kd";
	private String source = "E_BAY+OR+CRAIG";
	private String location = "LAX";
	private String head = "ford";
	private String limit = "10";
	private String priceLow = "0";
	private String priceHigh = "200";
	
	private String urlString = "http://api.3taps.com/search?" +
			"source=%s" +
			"&location=%s" +
			"&heading=%s" +
			"&authID=%s" +
			"&rpp=%s" +
			"&price=%s-%s";
	
	public static final String TAG = "API_CALLS_class:  ";
	
	public URL constructURL(String source, String location, String head, String limit, String priceLow, String priceHigh){
		@SuppressWarnings("static-access")
		String tmpUrl = urlString.format(urlString, source, location, head, APIKEY, limit, priceLow, priceHigh);
		URL myUrl = null;
		try {
		 myUrl = new URL(tmpUrl);
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return myUrl;
	}
	
	public String getURLcontents(URL url) throws IOException{
		String response = "failed";
		HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
		Log.v(TAG, "Opening connection: " + url.toString());
		try {
			InputStream in = new BufferedInputStream(urlConnection.getInputStream());
			response = new Scanner(in).useDelimiter("\\A").next();
		}
		catch (Exception e) {
			urlConnection.disconnect();
			return response = "failed";
		}
		finally {
			urlConnection.disconnect();
			Log.v(TAG, "Closed connection");
		}
		return response;
	}
	
}
